<template>
  <div class="user-dep-container">
    <!-- 左侧 -->
    <div class="user-dep-container-left">
      <div class="title">选择:</div>
      <div class="container">
        <!-- 搜索区域 -->
        <a-input ref="userNameInput" v-model.trim="queryParam.username" placeholder="搜索" allow-clear @keyup.enter.native="handleSearch">
          <a-icon slot="prefix" type="search" />
        </a-input>
        <!-- 面包屑 -->
        <div class="nav" v-if="navList && navList.length > 0">
          <a-icon type="double-left" v-if="navList && navList.length > 3 && (navList.length - 3 - navListIndex > 0)" @click="frontClick" />
          <span class="item" :class="{item_span: navList && navList.length > 3 && (navList.length - 3 - navListIndex > 0)}" v-for="(item, index) in calNavList" :key="index" @click="changeDataSource(index)">{{item.title}}</span>
          <a-icon type="double-right" v-if="navList && navList.length > 3 && navListIndex > 0" @click="afterClick" />
          <a-icon type="close-circle" v-if="navList && navList.length === 1" @click="handleClear" />
        </div>
        <!-- 部门展示 -->
        <div class="dep-content" v-if="!userShow">
          <div class="item" v-for="(item, index) in dataSource" :key="index" @click="setDep(item)" :class="{active: isActive(item)}">
            <span>{{item.title}}</span>
            <span class="icon" @click.stop="getCurDep(item)" v-if="!isActive(item)">
              <a-icon type="cluster" />
              <span>下级</span>
            </span>
          </div>
        </div>
        <!-- 人员展示 -->
        <div class="user-content" v-if="userShow && plainOptions && plainOptions.length">
          <a-row>
            <a-col :span="24">
              <a-checkbox :checked="checkAll" @change="onCheckAllChange">
                全选
              </a-checkbox>
            </a-col>
          </a-row>
          <a-checkbox-group v-model="checkedList" @change="onChange">
            <a-row>
              <a-col :span="24" v-for="(item, index) in plainOptions" :key="index">
                <a-checkbox :value="item.id" @change="onChangeEach">
                  <img :src="item.avatar">
                  <span>{{item.username}}</span>
                </a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </div>
      </div>
    </div>
    <!-- 右侧 -->
    <div class="user-dep-container-right">
      <div class="title">已选:</div>
      <div class="container">
        <div v-for="(item, index) in userDepList" class="user-dep">
          <!-- 部门 -->
          <div class="dep" v-if="item.children || item.parentId">
            <a-icon type="folder" theme="filled" class="icon" />
            <span>{{item.title}}</span>
            <a-icon type="close-circle" @click="handleUserDepClear(index)" class="clear" />
          </div>
          <!-- 人员 -->
          <div class="user" v-else>
            <img :src="item.avatar">
            <span>{{item.username}}</span>
            <a-icon type="close-circle" @click="handleUserDepClear(index)" class="clear" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import { queryTreeListByLength } from '@/api/api';
  import { getAction } from '@/api/manage';
  import { queryDepartTree } from './userDepSex.js'
  export default{
    data(){
      return {
        queryParam: {
          username: "",      //搜索字段
        },
        checkAll: false,     //人员全选字段
        checkedList: [],     //人员选中数据源
        plainOptions: [],    //人员数据源(搜索)
        plainOptionsOri: [], //人员数据源
        dataSource: [],      //部门数据源(搜索)
        dataSourceOri: [],   //整体数据源
        navList: [],         //面包屑数据源
        calNavList: [],      //面包屑当前要展示的数据
        userShow: false,     //是否显示人员(部门)
        navListIndex: 0,     //面包屑左移个数
        searchDataOri: [],   //部门数据源
        userDepList: [],     //已选数据
        selectOptions: []    //回显数据
      }
    },
    watch: {
      selectOptions: {
        handler(val){
          //回显已选中数据
          this.userDepList = [...this.userDepList, ...val];
        }
      }
    },
    mounted(){
      //获取tree树
      this.queryDepartTree()
    },
    methods: {
      queryDepartTree() {
        queryTreeListByLength({orgCode:'A03'}).then((res) => {
          if (res.success) {
            this.dataSource = res.result || [];
            this.dataSourceOri = res.result || [];
            this.searchDataOri = this.dataSource;
          }
        })
      },
      //人员选中切换
      onChange(checkedList) {
        //全选
        this.checkAll = checkedList.length === this.plainOptions.length;
      },
      onChangeEach(e){
        if(e.target.checked){
          //新增
          let curChecked = this.plainOptions.find(item => {
            return item.id === e.target.value
          })
          this.userDepList.push(curChecked);
        }else{
          //删除
          let index = this.userDepList.findIndex(item => {
            return item.id === e.target.value
          })
          this.userDepList.splice(index, 1);
        }
      },
      //人员全选
      onCheckAllChange(e) {
        Object.assign(this, {
          checkedList: e.target.checked ? this.plainOptions.map(item => item.id) : [],
          checkAll: e.target.checked,
        });
        this.handleCheckList();
      },
      handleCheckList(){
        let plainOptionsIdList = this.plainOptions.map(item => item.id);
        //人员
        let plainOptions = this.plainOptions.filter(item => this.checkedList.indexOf(item.id) > -1);
        //已选中去除本部门下的人
        let result = this.userDepList.filter(item => {
          return plainOptionsIdList.indexOf(item.id) === -1;
        });
        //已选区域更新
        this.userDepList = [...result, ...plainOptions];
      },
      //点击下级
      getCurDep(item){
        //面包屑中添加当前部门
        this.navList.push(item);
        //重新计算面包屑展示
        this.getCalNavList();
        //设置部门数据源
        this.dataSource = item.children;
        //设置部门数据源(搜索)
        this.searchDataOri = this.dataSource;
        //人员
        if(!item.children){
          this.userShow = true;
          this.loadData(item.id)
        }
      },
      //添加部门
      setDep(item){
        if(this.isActive(item)) return;
        //部门展示在列表最前
        let index = this.userDepList.findIndex(item => !item.children && !item.parentId);
        if(index > -1){
          //存在人员
          this.userDepList.splice(index, 0, item);
        }else{
          //均为部门
          this.userDepList.push(item);
        }
      },
      //是否为已选中
      isActive(item){
        return this.userDepList.some(curItem => {
          return curItem.id === item.id;
        })
      },
      loadData(departId) {
        let params = {
          pageNo: 1,
          pageSize: 999,
          departId
        }
        getAction('/sys/user/queryUserComponentData', params).then(res=>{
          if (res.success) {
            //人员数据源
            this.plainOptions = res.result.records || [];
            //人员数据源(搜索)
            this.plainOptionsOri = res.result.records || [];

            let plainOptionsIdList = this.plainOptions.map(item => item.id);
            //展示人员
            let checkedList = this.userDepList.filter(item => {
              return plainOptionsIdList.indexOf(item.id) > -1
            })
            //处理人员中全选
            this.checkedList = checkedList.map(item => {
              return item.id
            })
            //回显时，全选展示
            this.checkAll = this.checkedList.length === this.plainOptions.length;
          }
        })
      },
      //面包屑中前移
      frontClick(){
        this.navListIndex++;
        this.getCalNavList();
      },
      //面包屑中后移
      afterClick(){
        this.navListIndex--;
        this.getCalNavList();
      },
      getCalNavList(){
        if(!this.navList || !this.navList.length){
          this.calNavList = [];
          return;
        }
        if(this.navList.length <= 3){
          this.calNavList = this.navList;
          return;
        }
        //面包屑展示
        this.calNavList = this.navList.slice(this.navList.length-3-this.navListIndex, this.navList.length-this.navListIndex);
      },
      //点击面包屑中标题，跳转当前页
      changeDataSource(index){
        //当前项的角标
        index = this.navList.length - this.navListIndex - this.calNavList.length + index;
        //若为最后一项，不做处理
        if(index+1 === this.navList.length) return;
        //跳转肯定为部门
        this.userShow = false;
        this.dataSource = this.navList[index].children;
        this.searchDataOri = this.dataSource;
        //去掉该项后的面包屑
        this.navList.splice(index+1, this.navList.length);
        //面包屑前移项重置
        this.navListIndex = 0;
        this.getCalNavList();
      },
      handleClear(){
        this.dataSource = this.dataSourceOri;
        this.searchDataOri = this.dataSource;
        this.navList = [];
        this.navListIndex = 0;
      },
      handleSearch(){
        if(!this.userShow){
          if(!this.queryParam.username){
            this.dataSource = this.searchDataOri;
            return;
          }
          this.dataSource = this.searchDataOri.filter(item => {
            return item.title.indexOf(this.queryParam.username) > -1;
          })
        }else{
          if(!this.queryParam.username){
            this.plainOptions = this.plainOptionsOri;
            return;
          }
          this.plainOptions = this.plainOptionsOri.filter(item => {
            return item.username.indexOf(this.queryParam.username) > -1;
          })
        }
      },
      handleUserDepClear(index){
        this.userDepList.splice(index, 1);
        //人员处理
        let plainOptionsIdList = this.plainOptions.map(item => item.id);
        let result = this.userDepList.filter(item => {
          return plainOptionsIdList.indexOf(item.id) > -1;
        });
        this.checkedList = result.map(item => item.id);
        this.checkAll = this.checkedList.length === this.plainOptions.length;
      }
    }
  }
</script>

<style lang="less" scoped>
//解决图片文字出现蓝底的问题
.user-dep-container{
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.user-dep-container{
  width: 66%;
  margin-left: 17%;
  display: flex;
  .user-dep-container-left, .user-dep-container-right{
    width: 48%;
    .title{
      margin-bottom: 10px;
    }
  }
  img{
    width: 26px;
    height: 26px;
    border-radius: 50%;
    margin-right: 4px;
  }
  .user-dep-container-right{
    margin-left: 4%;
    .container{
      overflow-y: auto;
      .user-dep{
        margin: 4px 0;
        .dep, .user{
          display: flex;
          align-items: center;
          position: relative;
          .icon{
            color: #aee4fa;
            font-size: 18px;
            margin-right: 4px;
          }
          .clear{
            position: absolute;
            right: 0;
            color: #bab8c1;
          }
        }
      }
    }
  }
  .container{
    background-color: #fafafa;
    border: 1px solid #e8e8e8;
    height: 300px;
    padding: 10px;
    border-radius: 4px;
    .user-content{
      margin-top: 10px;
      height: 210px;
      overflow-y: auto;
      .ant-checkbox-wrapper, .ant-col-24{
        margin: 1px 0;
      }
    }
    .dep-content{
      margin-top: 10px;
      overflow-y: auto;
      height: 210px;
      .item{
        display: flex;
        justify-content: space-between;
        cursor: pointer;
        margin-bottom: 2px;
        .icon{
          color: #1890FF;
        }
      }
      .active{
        background-color: #e6f7ff;
      }
    }
    .nav{
      font-size: 14px;
      margin: 10px 0;
      display: flex;
      /deep/.anticon{
        margin: 0 4px;
        cursor: pointer;
        display: flex;
        align-items: center;
      }
      .item, .item_span{
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: pointer;
        &:not(:last-child){
          color: #1890FF;
        }
      }
      .item{
        &:nth-child(n+2){
          &::before{
            content: ">";
            color: rgba(0, 0, 0, 0.65);
          }
        }
      }
      .item_span{
        &:nth-child(2){
          &::before{
            content: "";
          }
        }
      }
    }
  }
}
</style>